<template>
  <comForm :form-info="props.formInfo" />
  <div style="margin-top: 16px">
    <fileUpload
      ref="fileUploadRef"
      v-model="fileList"
      v-model:file-lists="filesList"
      accept=".png, .jpg, .pdf, .docx, .doc, .xlsx, .xls"
      :filter-secret-level="formInfo.secretLevel"
      upload-permission="pms:order-attachment:save"
      del-permission="pms:order-attachment:delete"
      @delete-file="deleteFile"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, defineProps, watch } from 'vue';
  import fileUpload from '@/common/components/file-upload/index.vue';
  import {
    saveOrderFile,
    getPmsOrderFileList,
    delOrderFile,
  } from '@/api/purchase-order/purchaseOrderPreparation';
  import { uploadFile } from '@/api/file';
  import { Message } from '@arco-design/web-vue';
  import comForm from './com-form.vue';

  const props = defineProps({
    formInfo: {
      type: Object,
      default: null,
    },
  });
  const fileUploadRef = ref();
  const fileList = ref([]);
  const filesList = ref([]);
  const deleteFile = async (fileItem: any) => {
    const res: any = await delOrderFile(fileItem.id);
    if (res.code === 200) {
      Message.success('删除成功');
      initFile();
    }
  };
  const initFile = async () => {
    const res: any = await getPmsOrderFileList({
      pmsOrderId: props.formInfo.id,
    });
    if (res.code === 200) {
      fileList.value = res.data.map((item: any) => {
        item.name = item.filesName;
        return item;
      });
    }
  };
  const saveFile = async () => {
    await fileUploadRef.value.validate();
    const arr = await fileUp(filesList.value);
    const saveR = await saveFile1(arr);
    if (saveR) {
      filesList.value = [];
      return true;
    }
    return false;
  };
  const saveFile1 = async (arr: any[]) => {
    console.log('arr', arr);
    const promises: Promise<any>[] = [];
    arr.forEach((item: any) => {
      const params = {
        pmsOrderId: props.formInfo.id,
        filesName: item.fileName,
        filesUrl: item.data,
        secretLevel: item.secretLevel,
      };
      promises.push(
        new Promise((resolve, reject) => {
          saveOrderFile(params)
            .then((res: any) => {
              resolve(res);
            })
            .catch((res: any) => {
              reject(res);
            });
        })
      );
    });
    return Promise.all(promises);
  };
  const fileUp = async (arr: any[]) => {
    const promises: Promise<any>[] = [];
    arr.forEach((item: any) => {
      if (item.file && item.flg !== '1') {
        const formData = new FormData();
        formData.append('file', item.file);
        promises.push(
          new Promise((resolve, reject) => {
            uploadFile(formData, {
              secretLevel: item.secretLevel,
              path: item.name,
            })
              .then((res: any) => {
                resolve({
                  ...res,
                  fileName: item.name,
                  secretLevel: item.secretLevel,
                });
              })
              .catch((res: any) => {
                reject(res);
              });
          })
        );
      }
    });
    return Promise.all(promises);
  };
  watch(
    () => props.formInfo,
    () => {
      if (props.formInfo.id) {
        initFile();
      }
    },
    { deep: true, immediate: true }
  );
  defineExpose({ saveFile, initFile });
</script>
